package com.ruoyi.web.controller.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.platformusers.domain.PlatformUsers;
import com.ruoyi.platformusers.service.IPlatformUsersService;
import com.ruoyi.teacher.domain.DzTeacherList;
import com.ruoyi.teacher.service.IDzTeacherListService;
import com.ruoyi.web.controller.wechatlogin.HomeController;
import com.ruoyi.web.controller.wechatlogin.HttpsRequest;
import com.ruoyi.web.controller.wechatlogin.Login_Bean;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.*;

/**
 * 平台用户信息Controller
 *
 * @author ruoyi
 * @date 2024-01-05
 */
@RestController
@RequestMapping("/wechat/platformusers")
public class WeChatPlatformUsersController extends BaseController {
    @Autowired
    private IPlatformUsersService platformUsersService;

    /**
     * 查询平台用户信息列表
     */

    @GetMapping("/list")
    public TableDataInfo list(PlatformUsers platformUsers) {
        startPage();
        List<PlatformUsers> list = platformUsersService.selectPlatformUsersList(platformUsers);
        return getDataTable(list);
    }



    @Autowired
    private IDzTeacherListService dzTeacherListService;

    @PostMapping("/updataimgsfile")
    public AjaxResult updatafile(PlatformUsers platformUsers, @RequestParam("imgsfile") MultipartFile file) throws Exception {

        Long userId = platformUsers.getUserId();
        if (!file.isEmpty()) {

            String Remark = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            platformUsers.setUserId(userId);
            platformUsers.setAvatar(Remark);
            PlatformUsers platformUsers1 = platformUsersService.selectPlatformUsersByUserId(userId);
            if (platformUsers1!=null) {
                DzTeacherList dzTeacherList=new DzTeacherList();
                dzTeacherList.setRemark1(Remark);
                dzTeacherList.setId(Long.parseLong(platformUsers1.getTeacherId()));
                dzTeacherListService.updateDzTeacherList(dzTeacherList);
            }



            return   toAjax(platformUsersService.updatePlatformUsers(platformUsers));

        }else{
            return error("上传图片异常，请联系管理员");
        }

    }



    /**
     * 导出平台用户信息列表
     */

    @PostMapping("/export")
    public void export(HttpServletResponse response, PlatformUsers platformUsers) {
        List<PlatformUsers> list = platformUsersService.selectPlatformUsersList(platformUsers);
        ExcelUtil<PlatformUsers> util = new ExcelUtil<PlatformUsers>(PlatformUsers.class);
        util.exportExcel(response, list, "平台用户信息数据");
    }

    /**
     * 获取平台用户信息详细信息
     */

    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        return success(platformUsersService.selectPlatformUsersByUserId(userId));
    }

    /**
     * 新增平台用户信息
     */


    @PostMapping
    public AjaxResult add(@RequestBody PlatformUsers platformUsers) {
        return toAjax(platformUsersService.insertPlatformUsers(platformUsers));
    }

    /**
     * 修改平台用户信息
     */


    @PutMapping
    public AjaxResult edit(@RequestBody PlatformUsers platformUsers) {
        return toAjax(platformUsersService.updatePlatformUsers(platformUsers));
    }

    /**
     * 删除平台用户信息
     */

    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(platformUsersService.deletePlatformUsersByUserIds(userIds));
    }

    private static Logger logger = LoggerFactory.getLogger(HomeController.class);
    PlatformUsers platformUsersall;


    @PostMapping("/login")
    public AjaxResult login(@RequestBody PlatformUsers dzPlatformUsers) {
        String userName = dzPlatformUsers.getUserName();
        PlatformUsers newdzPlatformUsers = new PlatformUsers();
        newdzPlatformUsers.setUserName(userName);

        List<PlatformUsers> list = platformUsersService.selectPlatformUsersList(dzPlatformUsers);
        if (list.size() > 0) {

            PlatformUsers dzPlatformUsers1 = list.get(0);
            if (dzPlatformUsers1.getUserName().equals(dzPlatformUsers.getUserName())) {
                return success(dzPlatformUsers1);
            } else {
                return error("用户/密码错误！");
            }

        } else {
            return error("用户不存在！");
        }

    }

    @PostMapping("/wxlogin")
    public AjaxResult login(@RequestBody Login_Bean login_bean) {

        com.alibaba.fastjson.JSONObject res =   getPhoneNumber(login_bean.getPhone_encryptedData(),login_bean.getCode(),login_bean.getPhone_iv());
        String phoneNumber = (String) res.get("phoneNumber");

        PlatformUsers newdzPlatformUsers = new PlatformUsers();
        newdzPlatformUsers.setPhonenumber(phoneNumber);
        newdzPlatformUsers.setNickName("微信用户"+phoneNumber);
        List<PlatformUsers> list = platformUsersService.selectPlatformUsersList(newdzPlatformUsers);
        if (list.size()>0) {
            System.out.println("存在");
            //存在这个人，返回数据
            platformUsersall = list.get(0);
        } else {
            System.out.println("不存在");
            //创建这个人，返返回数据
            int i = platformUsersService.insertPlatformUsers(newdzPlatformUsers);
            if (i>0) {
                List<PlatformUsers> list2 = platformUsersService.selectPlatformUsersList(newdzPlatformUsers);
                platformUsersall = list2.get(0);
            }


        }

//        System.out.println(platformUsers);
        return AjaxResult.success(platformUsersall);
    }

    public com.alibaba.fastjson.JSONObject getPhoneNumber(String encryptedData, String code, String iv) {
        //传入code后然后获取openid和session_key的，把他们封装到json里面
        com.alibaba.fastjson.JSONObject json = getSessionKeyOropenid(code);
        String session_key = "";
        if (json != null) {

            session_key = json.getString("session_key");
            // 被加密的数据

            byte[] dataByte = new Base64().decode(encryptedData );
            // 加密秘钥
            byte[] keyByte = new Base64().decode(session_key);
            // 偏移量
            byte[] ivByte = new Base64().decode(iv);
            try {
                // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
                int base = 16;
                if (keyByte.length % base != 0) {
                    int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                    byte[] temp = new byte[groups * base];
                    Arrays.fill(temp, (byte) 0);
                    System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                    keyByte = temp;
                }
                // 初始化
                Security.addProvider(new BouncyCastleProvider());
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
                AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
                parameters.init(new IvParameterSpec(ivByte));
                cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
                byte[] resultByte = cipher.doFinal(dataByte);
                if (null != resultByte && resultByte.length > 0) {
                    String result = new String(resultByte, "UTF-8");
                    return com.alibaba.fastjson.JSONObject.parseObject(result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取微信小程序 session_key 和 openid
     *
     * @param code 调用微信登陆返回的Code
     * @return
     */
    public static com.alibaba.fastjson.JSONObject getSessionKeyOropenid(String code) {
        //微信端登录code值
        String wxCode = code;
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";  //请求地址 https://api.weixin.qq.com/sns/jscode2session
        Map<String, String> requestUrlParam = new HashMap<String, String>();
        requestUrlParam.put("appid", "wx9987948375c00cc0");  //开发者设置中的appId
        requestUrlParam.put("secret", "50fb52e2bedc9b3991afe688ae6e2c62"); //开发者设置中的appSecret
        requestUrlParam.put("js_code", wxCode); //小程序调用wx.login返回的code
        requestUrlParam.put("grant_type", "authorization_code");    //默认参数 authorization_code

        //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
        JSONObject jsonObject = JSON.parseObject(sendPost(requestUrl, requestUrlParam));
        return jsonObject;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, Map<String, ?> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        String param = "";
        Iterator<String> it = paramMap.keySet().iterator();

        while (it.hasNext()) {
            String key = it.next();
            param += key + "=" + paramMap.get(key) + "&";
        }

        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}
